Flask 学习 您所在的位置:网站首页 argument 参数 Flask 学习

Flask 学习

2023-07-20 08:36| 来源: 网络整理| 查看: 265

前言

在校验请求参数的时候,除了一些基本的required=True, type类型外,还会遇到一些校验,比如是否为空,字符串长度,以及一些自定义的参数规则。

add_argument 参数

下面是add_argument 可以使用的参数,部分源码如下:

class Argument(object): """ :param name: Either a name or a list of option strings, e.g. foo or -f, --foo. :param default: The value produced if the argument is absent from the request. :param dest: The name of the attribute to be added to the object returned by :meth:`~reqparse.RequestParser.parse_args()`. :param bool required: Whether or not the argument may be omitted (optionals only). :param action: The basic type of action to be taken when this argument is encountered in the request. Valid options are "store" and "append". :param ignore: Whether to ignore cases where the argument fails type conversion :param type: The type to which the request argument should be converted. If a type raises an exception, the message in the error will be returned in the response. Defaults to :class:`unicode` in python2 and :class:`str` in python3. :param location: The attributes of the :class:`flask.Request` object to source the arguments from (ex: headers, args, etc.), can be an iterator. The last item listed takes precedence in the result set. :param choices: A container of the allowable values for the argument. :param help: A brief description of the argument, returned in the response when the argument is invalid. May optionally contain an "{error_msg}" interpolation token, which will be replaced with the text of the error raised by the type converter. :param bool case_sensitive: Whether argument values in the request are case sensitive or not (this will convert all values to lowercase) :param bool store_missing: Whether the arguments default value should be stored if the argument is missing from the request. :param bool trim: If enabled, trims whitespace around the argument. :param bool nullable: If enabled, allows null value in argument. """ def __init__(self, name, default=None, dest=None, required=False, ignore=False, type=text_type, location=('json', 'values',), choices=(), action='store', help=None, operators=('=',), case_sensitive=True, store_missing=True, trim=False, nullable=True): self.name = name self.default = default self.dest = dest self.required = required self.ignore = ignore self.location = location self.type = type self.choices = choices self.action = action self.help = help self.case_sensitive = case_sensitive self.operators = operators self.store_missing = store_missing self.trim = trim self.nullable = nullable nullable=False 不允许为None

required=True 设置该参数是必传项, nullable=False 是设置该参数不允许为None

class Register(Resource): def post(self): # 校验入参 parser = reqparse.RequestParser() parser.add_argument('username', required=True, type=str, nullable=False, help='username is required') parser.add_argument('password', required=True, type=str, nullable=False, help='password is required') args = parser.parse_args() # # 获取入参 # data = request.get_json() print(f'请求入参:{args}') return jsonify({ "code": 0, "msg": "success" }) # 注册 api.add_resource(Register, '/api/v1/register')

需注意的是这里是不能为null, 传空字符串还是可以的。

default=''设置默认值

对address 参数设置默认值,当用户没传address 参数的时候,就会取默认值

def post(self): # 校验入参 parser = reqparse.RequestParser() parser.add_argument('username', required=True, type=str, nullable=False, help='username is required') parser.add_argument('password', required=True, type=str, nullable=False, help='password is required') parser.add_argument('address', default='上海市', type=str, help='address invalid') args = parser.parse_args() print(f'请求入参:{args}')

请求示例

POST http://127.0.0.1:5000/api/v1/register HTTP/1.1 User-Agent: Fiddler Host: 127.0.0.1:5000 Content-Type: application/json Content-Length: 56 { "username": "test", "password" : "111111" }

args 得到的参数

{'username': 'test', 'password': '111111', 'address': '上海市'} choices 设置参数可选值

比如性别设置可选项:男、女

def post(self): # 校验入参 parser = reqparse.RequestParser() parser.add_argument('username', required=True, type=str, nullable=False, help='username is required') parser.add_argument('password', required=True, type=str, nullable=False, help='password is required') parser.add_argument('sex', choices=["男", "女"], type=str, help='sex invalid') args = parser.parse_args() print(f'请求入参:{args}')

请求示例,sex不是可选项的时候会报400

POST http://127.0.0.1:5000/api/v1/register HTTP/1.1 User-Agent: Fiddler Host: 127.0.0.1:5000 Content-Type: application/json Content-Length: 73 { "username": "test", "password" : "111111", "sex": "x" } HTTP/1.1 400 BAD REQUEST Server: Werkzeug/2.2.2 Python/3.8.5 Date: Thu, 01 Sep 2022 13:40:14 GMT Content-Type: application/json Content-Length: 57 Connection: close { "message": { "sex": "sex invalid" } } 设置字符串长度

比如限制 password 是 6-16 位,由于 add_argument 没提供对应的方法,需我们自定义参数校验类型

class Register(Resource): @staticmethod def password_validate(value, name): if len(value) < 6 or len(value) > 16: raise ValueError(name + '参数长度不合法') return value def post(self): # 校验入参 parser = reqparse.RequestParser() parser.add_argument('username', required=True, type=str, nullable=False, help='username invalid') parser.add_argument('password', required=True, type=self.password_validate, nullable=False, help='password invalid must 6-16') # parser.add_argument('sex', choices=["男", "女"], type=str, help='sex invalid') args = parser.parse_args() print(f'请求入参:{args}')

如果密码长度小于6位,会返回400

POST http://127.0.0.1:5000/api/v1/register HTTP/1.1 User-Agent: Fiddler Host: 127.0.0.1:5000 Content-Type: application/json Content-Length: 55 { "username": "test", "password" : "12345" } HTTP/1.1 400 BAD REQUEST Server: Werkzeug/2.2.2 Python/3.8.5 Date: Thu, 01 Sep 2022 14:04:30 GMT Content-Type: application/json Content-Length: 76 Connection: close { "message": { "password": "password invalid must 6-16" } }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有